package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {

    //远程调用的 地址
    // public static final String PAYMENY_URL = "http://localhost:8001"; 写死ip地址的
    // cloud-provider-service 这个是项目的名称,表示访问的是cloud-provider-payment8001集群项目
    public static final String PAYMENY_URL = "http://cloud-provider-service";
    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value ="customer/payment/create")
    public CommonResult<Payment> create (Payment payment){
        /**
         param1 请求地址，param2 请求参数， param3 返回类型
         */
        return restTemplate.postForObject(PAYMENY_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping(value ="customer/payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
        log.info("进入查询");
        return restTemplate.getForObject(PAYMENY_URL + "/payment/get/" + id, CommonResult.class);
    }


    /**
     * 演示getForEntity,这个不重要
     * 获取返回码是什么
     */
    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getPayment2(@PathVariable("id") Long id)
    {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENY_URL+"/payment/get/"+id,CommonResult.class);

        if(entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }else{
            return new CommonResult<>(444,"操作失败");
        }
    }
}
